package com.fengyi.library.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 熔断器状态控制器
 * 使用Spring Boot Actuator提供熔断器状态信息
 */
@RestController
@RequestMapping("/api/circuit-breaker-status")
public class CircuitBreakerStatusController {

    @Autowired
    private CircuitBreakerFactory circuitBreakerFactory;
    
    /**
     * 获取熔断器状态
     * @return 熔断器状态
     */
    @GetMapping
    public Map<String, Object> getCircuitBreakerStatus() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建一个熔断器实例来测试状态
            var circuitBreaker = circuitBreakerFactory.create("serviceInfoCircuitBreaker");
            result.put("status", "available");
            result.put("message", "熔断器服务可用");
            
            // 添加熔断器信息
            Map<String, Object> info = new HashMap<>();
            info.put("name", "serviceInfoCircuitBreaker");
            info.put("type", circuitBreaker.getClass().getSimpleName());
            result.put("circuitBreaker", info);
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "获取熔断器状态失败: " + e.getMessage());
            result.put("error", e.getClass().getName());
        }
        
        return result;
    }
    
    /**
     * 获取指定熔断器状态
     * @param name 熔断器名称
     * @return 熔断器状态
     */
    @GetMapping("/{name}")
    public Map<String, Object> getCircuitBreakerStatus(@PathVariable String name) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建指定名称的熔断器实例
            var circuitBreaker = circuitBreakerFactory.create(name);
            result.put("status", "available");
            result.put("message", "熔断器 " + name + " 可用");
            
            // 添加熔断器信息
            Map<String, Object> info = new HashMap<>();
            info.put("name", name);
            info.put("type", circuitBreaker.getClass().getSimpleName());
            result.put("circuitBreaker", info);
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "获取熔断器 " + name + " 状态失败: " + e.getMessage());
            result.put("error", e.getClass().getName());
        }
        
        return result;
    }
} 